﻿using System;
using System.Windows.Input;
using System.Collections.Generic;

namespace AccessControl.Wpf.Commands
{
	class CommandBaseOfT<T> : ICommand
	{
		#region Fields

		Action<T> _actionToExecute;

		#endregion

		#region Public Constructor

		public CommandBaseOfT(Action<T> actionToExecute)
		{
			_actionToExecute = actionToExecute;
		}

		#endregion

		#region ICommand Members

		public bool CanExecute(object parameter)
		{
			return (_actionToExecute != null);
		}

		public event EventHandler CanExecuteChanged;

		public void Execute(object parameter)
		{
			_actionToExecute.Invoke(ParseParameter(parameter, typeof(T)));
		}

		#endregion

		#region Private Members
	
		private T ParseParameter(object parameter, Type parseAsType)
		{
			if (parameter == null) 
				return default(T);

			if (parseAsType.IsEnum)
			{
				return (T)Enum.Parse(parseAsType, Convert.ToString(parameter), true);
			}
			else if (parseAsType.IsValueType)
			{
				return (T)Convert.ChangeType(parameter, parseAsType, null);
			}
			else
			{
				return (T)parameter;
			}
		}

		#endregion
	}
}
